package com.hmdp.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR;

    static {
        THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(16, 32, 60L,
                TimeUnit.SECONDS, new ArrayBlockingQueue(100));
    }

    /**
     * 根据Id查询店铺信息
     *
     * @param id 店铺id
     * @return 返回店铺信息
     */
    @Override
    public Shop queryShopById(Long id) {
        // 判断redis是否包含店铺信息
        String getCachedShop = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isBlank(getCachedShop)) {
            // 缓存为空""或者Null
            return null;
        }
        // 获取缓存
        RedisData<Shop> redisData = JSONUtil.toBean(getCachedShop, new TypeReference<RedisData<Shop>>() {
        }, false);
        // 获取店铺信息
        Shop shop = redisData.getData();
        // 获取逻辑过期时间
        Long expireTime = redisData.getExpireTime();
        LocalDateTime now = LocalDateTime.now();
        boolean isExpire = now.isAfter(LocalDateTime.ofInstant(Instant.ofEpochSecond(expireTime), ZoneId.systemDefault()));
        if (!isExpire) {
            return shop;
        }
        String key = LOCK_SHOP_KEY + id;
        boolean tryLock = tryLock(key);
        // 为空创建一个新的线程缓存重建,并发拿锁
        if (tryLock) {
            THREAD_POOL_EXECUTOR.submit(() -> {
                try {
                    RedisData<Shop> shopRedisData = new RedisData<>();
                    Shop renewShop = baseMapper.selectById(id);
                    shopRedisData.setData(renewShop);
                    shopRedisData.setExpireTime(LocalDateTime.now().plusMinutes(10L).toEpochSecond(ZoneOffset.of("+8")));
                    if (ObjectUtil.isNotEmpty(renewShop)) {
                        // 添加到redis中
                        String cachedRedisData = JSONUtil.toJsonStr(shopRedisData);
                        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, cachedRedisData);
                    } else {
                        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_SHOP_TTL, TimeUnit.MINUTES);
                    }
                } catch (Exception e) {
                    log.error("出现异常：{}", e);
                } finally {
                    unlock(key);
                }

            });

        }
        return shop;
    }

    public void preHotCache(Long id) {
        Shop shop = this.baseMapper.selectById(id);
        RedisData<Shop> shopRedisData = new RedisData<>();
        shopRedisData.setData(shop);
        shopRedisData.setExpireTime(LocalDateTime.now().plusMinutes(10L).toEpochSecond(ZoneOffset.of("+8")));
        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + shopRedisData.getData().getId(), JSONUtil.toJsonStr(shopRedisData));
    }

    /**
     * 互斥锁
     *
     * @return 是否锁定成功
     */
    private boolean tryLock(String key) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.MINUTES));
    }

    /**
     * 释放锁
     *
     * @param key
     */
    private void unlock(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 更新店铺信息
     *
     * @param shop 店铺信息
     * @return 是否更新成功
     */
    @Override
    @Transactional
    public boolean updateShopById(Shop shop) {
        Shop selectShop = baseMapper.selectById(shop.getId());
        if (ObjectUtil.isEmpty(selectShop)) {
            return false;
        }
        // 修改店铺信息
        int updateById = baseMapper.updateById(shop);
        if (updateById < 0) {
            return false;
        }
        // 删除缓存
        if (!redisTemplate.delete(CACHE_SHOP_KEY + shop.getId())) {
            return false;
        }
        return true;
    }
}
